using System;
using System.Collections.Generic;
using System.Linq;

namespace Pay.Core {
    public static class IEnumerableExtension {
        public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) {
            if (items == null) throw new ArgumentNullException("items");
            if (action == null) throw new ArgumentNullException("action");

            foreach (var item in items)
                action(item);
        }
        public static void ForEach<T>(this IEnumerable<T> items, Action<T, int> action) {
            if (items == null) throw new ArgumentNullException("items");
            if (action == null) throw new ArgumentNullException("action");
            int i = 0;
            foreach (var item in items) {
                action(item, i);
                i++;
            }
        }
        /// <summary>
        /// 在EF修改状态时，一定要用此方法，用foreach会提示：集合已修改，可能无法执行枚举操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="action"></param>
        public static void DataForEach<T>(this IEnumerable<T> items, Action<T> action) {
            if (items == null) throw new ArgumentNullException("items");
            if (action == null) throw new ArgumentNullException("action");

            var count = items.Count();
            for (int i = count - 1; i > -1; i--)
                action(items.ElementAt(i));
        }
        /// <summary>
        /// 在EF修改状态时，一定要用此方法，用foreach会提示：集合已修改，可能无法执行枚举操作
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <param name="action"></param>
        public static void DataForEach<T>(this IEnumerable<T> items, Action<T, int> action) {
            if (items == null) throw new ArgumentNullException("items");
            if (action == null) throw new ArgumentNullException("action");

            var count = items.Count();
            for (int i = count - 1; i > -1; i--)
                action(items.ElementAt(i), i);
        }
    }
}
